const axios = require('axios');

// 配置自由服务器地址（需要根据实际情况修改）
const SERVER_URL = 'http://your-free-server.com/api';

// 云函数入口函数（实际应改为普通Node.js服务入口，这里保持兼容结构）
exports.main = async (event, context) => {
  const { action, data } = event;
  // 注意：自由服务器需要验证身份，这里需要传递认证信息（如token）
  const authHeader = { Authorization: `Bearer ${context.WX_CONTEXT.OPENID}` }; // 示例

  switch (action) {
    case 'add':
      return handleAdd(data, authHeader);
    case 'update':
      return handleUpdate(data, authHeader);
    case 'delete':
      return handleDelete(data.id)
    case 'getList':
      return handleGetList(data)
    case 'getDetail':
      return handleGetDetail(data.id)
    case 'addOperation':
      return handleAddOperation(data, baseData)
    case 'addProfit':
      return handleAddProfit(data, baseData)
    case 'getOperationHistory':
      return handleGetOperationHistory(data.financialId)
    case 'getProfitHistory':
      return handleGetProfitHistory(data.financialId)
    case 'getYearlyProfit':
      return handleGetYearlyProfit(data.year)
    case 'exportData':
      return handleExportData(data)
    case 'getOperationList':
      return handleGetOperationList(data)
    default:
      return {
        code: 400,
        msg: '未知的操作类型'
      }
  }
}

// 添加理财产品（原数据库add操作改为POST请求）
async function handleAdd(data, authHeader) {
  try {
    const response = await axios.post(`${SERVER_URL}/financial`, {
      ...data,
      create_user: authHeader.Authorization, // 从认证信息获取用户ID
      create_time: new Date().toISOString(),
      status: 1,
      is_deleted: 0,
      profit: 0
    }, { headers: authHeader });

    return {
      code: 200,
      msg: '添加成功',
      data: response.data.id
    };
  } catch (error) {
    return {
      code: 500,
      msg: '添加失败',
      error: error.response?.data || error.message
    };
  }
}

// 更新理财产品（原update操作改为PUT请求）
async function handleUpdate(data, authHeader) {
  try {
    const { id, ...updateData } = data;
    const response = await axios.put(`${SERVER_URL}/financial/${id}`, {
      ...updateData,
      update_time: new Date().toISOString()
    }, { headers: authHeader });

    return { code: 200, msg: '更新成功' };
  } catch (error) {
    return {
      code: 500,
      msg: '更新失败',
      error: error.response?.data || error.message
    };
  }
}

// 删除理财产品
async function handleDelete(id) {
  try {
    await financialCollection.doc(id).update({
      data: {
        is_deleted: 1,
        update_time: new Date()
      }
    })
    return {
      code: 200,
      msg: '删除成功'
    }
  } catch (error) {
    return {
      code: 500,
      msg: '删除失败',
      error
    }
  }
}

// 获取理财产品列表
async function handleGetList() {
  try {
    const { data } = await financialCollection
      .where({
        is_deleted: 0
      })
      .orderBy('create_time', 'desc')
      .get()
    return {
      code: 200,
      data
    }
  } catch (error) {
    return {
      code: 500,
      msg: '查询失败',
      error
    }
  }
}

// 获取理财产品详情
async function handleGetDetail(id) {
  try {
    const { data } = await financialCollection.doc(id).get()
    return {
      code: 200,
      data
    }
  } catch (error) {
    return {
      code: 500,
      msg: '查询失败',
      error
    }
  }
}

// 添加操作记录
async function handleAddOperation(data, baseData) {
  try {
    const result = await operateCollection.add({
      data: {
        ...data,
        ...baseData
      }
    })
    return {
      code: 200,
      msg: '添加成功',
      data: result._id
    }
  } catch (error) {
    return {
      code: 500,
      msg: '添加失败',
      error
    }
  }
}

// 添加收益记录
async function handleAddProfit(data, baseData) {
  try {
    // 获取理财产品信息
    const financial = await financialCollection.doc(data.financial_id).get();
    if (!financial.data) {
      return {
        code: 404,
        msg: '理财产品不存在'
      };
    }

    // 获取所有收益记录
    const { data: profits } = await profitCollection
      .where({
        financial_id: data.financial_id,
        is_deleted: 0
      })
      .get();

    // 计算总收益
    const totalProfit = profits.reduce((sum, item) => sum + item.profit, 0) + data.profit;
    
    // 计算年化收益率
    const startDate = new Date(financial.data.start_date);
    const now = new Date(data.submit_date);
    const days = Math.ceil((now - startDate) / (1000 * 60 * 60 * 24));
    const arr = (totalProfit / financial.data.money) * (365 / days) * 100;

    // 添加收益记录
    const result = await profitCollection.add({
      data: {
        ...data,
        arr: parseFloat(arr.toFixed(2)), // 保留两位小数
        ...baseData
      }
    });

    // 更新理财产品的总收益
    await updateFinancialProfit(data.financial_id);

    return {
      code: 200,
      msg: '添加成功',
      data: result._id
    };
  } catch (error) {
    return {
      code: 500,
      msg: '添加失败',
      error
    };
  }
}

// 获取操作历史
async function handleGetOperationHistory(financialId) {
  try {
    const { data } = await operateCollection
      .where({
        financial_id: financialId,
        is_deleted: 0
      })
      .orderBy('submit_date', 'desc')
      .get()
    
    return {
      code: 200,
      data
    }
  } catch (error) {
    return {
      code: 500,
      msg: '查询失败',
      error
    }
  }
}

// 获取收益历史
async function handleGetProfitHistory(financialId) {
  try {
    const { data } = await profitCollection
      .where({
        financial_id: financialId,
        is_deleted: 0
      })
      .orderBy('submit_date', 'desc')
      .get()
    
    return {
      code: 200,
      data
    }
  } catch (error) {
    return {
      code: 500,
      msg: '查询失败',
      error
    }
  }
}

// 获取年度收益统计
async function handleGetYearlyProfit(year) {
  try {
    const { data } = await profitCollection
      .aggregate()
      .match({
        is_deleted: 0,
        submit_date: {
          $regex: `^${year}`
        }
      })
      .lookup({
        from: 'financial_info',
        localField: 'financial_id',
        foreignField: '_id',
        as: 'financial'
      })
      .unwind('$financial')
      .group({
        _id: '$financial_id',
        name: { $first: '$financial.name' },
        total_profit: { $sum: '$profit' },
        avg_arr: { $avg: '$arr' },
        cost: { $first: '$financial.money' }
      })
      .project({
        _id: 1,
        name: 1,
        profit: '$total_profit',
        arr: '$avg_arr',
        cost: 1,
        year: year
      })
      .end();

    return {
      code: 200,
      data
    };
  } catch (error) {
    return {
      code: 500,
      msg: '查询失败',
      error
    };
  }
}

// 更新理财产品的总收益和年化率
async function updateFinancialProfit(financialId) {
  try {
    const { data: profits } = await profitCollection
      .where({
        financial_id: financialId,
        is_deleted: 0
      })
      .get();

    const totalProfit = profits.reduce((sum, item) => sum + item.profit, 0);

    await financialCollection.doc(financialId).update({
      data: {
        profit: totalProfit,
        update_time: new Date()
      }
    });

    return true;
  } catch (error) {
    console.error('更新产品收益失败:', error);
    return false;
  }
}

// 导出数据
async function handleExportData(data) {
  try {
    const { year } = data;
    
    // 获取理财产品列表
    const { data: products } = await financialCollection
      .where({
        is_deleted: 0
      })
      .get();

    // 获取收益记录
    const { data: profits } = await profitCollection
      .where({
        is_deleted: 0,
        submit_date: {
          $regex: `^${year}`
        }
      })
      .get();

    // 获取操作记录
    const { data: operations } = await operateCollection
      .where({
        is_deleted: 0,
        submit_date: {
          $regex: `^${year}`
        }
      })
      .get();

    // 构建导出数据
    const exportData = {
      products: products.map(product => ({
        name: product.name,
        bank: product.bank_id,
        type: product.type,
        money: product.money,
        profit: product.profit,
        arr: product.arr,
        buy_date: product.buy_date,
        end_date: product.end_date,
        remark: product.remark
      })),
      profits: profits.map(profit => ({
        financial_id: profit.financial_id,
        profit: profit.profit,
        arr: profit.arr,
        submit_date: profit.submit_date
      })),
      operations: operations.map(operation => ({
        financial_id: operation.financial_id,
        type: operation.type,
        money: operation.money,
        submit_date: operation.submit_date
      }))
    };

    return {
      code: 200,
      data: exportData
    };
  } catch (error) {
    return {
      code: 500,
      msg: '导出失败',
      error
    };
  }
}

// 获取操作记录列表
async function handleGetOperationList(data) {
  try {
    const { keyword, type, startDate, endDate, page = 1, pageSize = 20 } = data;
    
    // 构建查询条件
    const query = {
      is_deleted: 0
    };
    
    // 日期范围
    if (startDate && endDate) {
      query.submit_date = {
        $gte: startDate,
        $lte: endDate
      };
    }
    
    // 操作类型
    if (type) {
      query.type = type;
    }

    // 关联查询产品信息
    const { data: list } = await operateCollection
      .aggregate()
      .match(query)
      .lookup({
        from: 'financial_info',
        localField: 'financial_id',
        foreignField: '_id',
        as: 'financial'
      })
      .unwind({
        path: '$financial',
        preserveNullAndEmptyArrays: true
      })
      // 如果有关键字，过滤产品名称
      .match(keyword ? {
        'financial.name': db.RegExp({
          regexp: keyword,
          options: 'i'
        })
      } : {})
      .sort({
        submit_date: -1
      })
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .end();

    // 获取总数
    const { total } = await operateCollection
      .aggregate()
      .match(query)
      .lookup({
        from: 'financial_info',
        localField: 'financial_id',
        foreignField: '_id',
        as: 'financial'
      })
      .unwind({
        path: '$financial',
        preserveNullAndEmptyArrays: true
      })
      .match(keyword ? {
        'financial.name': db.RegExp({
          regexp: keyword,
          options: 'i'
        })
      } : {})
      .count('total')
      .end();

    return {
      code: 200,
      data: {
        list,
        total: total[0] ? total[0].total : 0
      }
    };
  } catch (error) {
    return {
      code: 500,
      msg: '查询失败',
      error
    };
  }
}